package com.uplift.mgt.building.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.uplift.common.base.BusinessException;
import com.uplift.common.base.ServiceReslut;
import com.uplift.common.utils.JExcelReadUtils;
import com.uplift.mgt.building.dao.BuildingMapper;
import com.uplift.mgt.building.dao.RealtyEarningsMapper;
import com.uplift.mgt.building.model.*;
import com.uplift.mgt.building.service.IBuildingService;
import com.uplift.mgt.building.service.IRealtyEarningsService;
import com.uplift.mgt.building.service.IRealtyInfoService;
import com.uplift.mgt.building.service.IRealtyLeaseService;
import com.uplift.mgt.customer.service.ICustomerService;
import com.uplift.sec.SecurityContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class RealtyEarningsServiceImpl implements IRealtyEarningsService {

	@Autowired
	private RealtyEarningsMapper realtyEarningsMapper;
	@Autowired
	private ICustomerService customerService;
	@Autowired
	private IRealtyInfoService realtyInfoService;
	@Autowired
	private IRealtyLeaseService realtyLeaseService;

	/** excle 每列的字段名称 */
	private String[] excel_cloum_names = new String[] {"客户名称","楼盘名称","房间号","日期","备注",
			"状态","税金","管理费","修缮费","日常杂费","代管费","设备维修费","手续费","其它费用","减免"};

	@Override
	public List<Map<String, Object>> queryRealtyEarnings(RealtyEarnings realtyEarnings) {
		PageHelper.startPage(realtyEarnings.getPage(), realtyEarnings.getLimit());
		ArrayList<String> dates = createDates(realtyEarnings);
		realtyEarnings.setDates(dates);

		return this.realtyEarningsMapper.selectRealtyEarnings(realtyEarnings);
	}

	@Override
	public List<Map<String, Object>> countEarnings(RealtyEarnings realtyEarnings) {
		if(StringUtils.isBlank(realtyEarnings.getCustomerName())) {
			return null;
		}
		if(CollectionUtils.isEmpty(realtyEarnings.getDates())) {
			return null;
		}

		return this.realtyEarningsMapper.countEarnings(realtyEarnings);
	}

	private ArrayList<String> createDates(RealtyEarnings realtyEarnings) {
		if(StringUtils.isBlank(realtyEarnings.getDateStart()) || StringUtils.isBlank(realtyEarnings.getDateEnd())) {
			return null;
		}

		String year = StringUtils.split(realtyEarnings.getDateStart(), "-")[0];
		int startMonth = Integer.valueOf(StringUtils.split(realtyEarnings.getDateStart(), "-")[1]).intValue();
		int endMonth = Integer.valueOf(StringUtils.split(realtyEarnings.getDateEnd(), "-")[1]).intValue();

		ArrayList<String> dates = new ArrayList<>();

		for (int i = startMonth; i <= endMonth; i++) {
			dates.add(year+"-" + String.format("%02d", i));
		}
		return dates;
	}

	@Override
	public ServiceReslut addRealtyEarnings(RealtyEarnings realtyEarnings) {
		Map<String, Object> sessionUser = SecurityContext.getSessionUser();
		if(sessionUser == null) {
			return ServiceReslut.newServiceReslut(0, "获取登录用户信息失败");
		}
		realtyEarnings.setCreateUserId((String) sessionUser.get("id"));

		realtyEarnings.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		realtyEarnings.setCreateTime(new Date());

		if(StringUtils.equals(realtyEarnings.getRealtyTypeCode(), "BUILD")) {		//更新房间收益
			updateRoomsEarnings(realtyEarnings);
		}

		return ServiceReslut.newServiceReslut(realtyEarningsMapper.insertRealtyEarnings(realtyEarnings), "");
	}

	/**
	 * 更新房间收益情况
	 * @param realtyEarnings
	 */
	public void updateRoomsEarnings(RealtyEarnings realtyEarnings) {
		if(realtyEarnings!=null) {
			if(StringUtils.isNotBlank(realtyEarnings.getRoomEarnings()) && StringUtils.isNotBlank(realtyEarnings.getId())) {
				RealtyErModel realtyErModel = new RealtyErModel();
				realtyErModel.setReId(realtyEarnings.getId());
				realtyEarningsMapper.deleteRoomsEarnings(realtyErModel);			//删除房间收益情况

				JSONArray rooms = JSONArray.parseArray(realtyEarnings.getRoomEarnings());
				JSONObject roomObj = null;
				for (int i = 0; i < rooms.size(); i++) {
					roomObj = rooms.getJSONObject(i);
					realtyErModel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
					realtyErModel.setRoomId(roomObj.getString("roomId"));
					realtyErModel.setRent(roomObj.getBigDecimal("rent"));
					realtyErModel.setLeaseManageCost(roomObj.getBigDecimal("leaseMangeCost"));

					realtyEarningsMapper.insertRoomsEarnings(realtyErModel);		//插入房间收益情况
				}
			}
		}
	}

	@Override
	public ServiceReslut updateRealtyEarnings(RealtyEarnings realtyEarnings) {

		if(StringUtils.equals(realtyEarnings.getRealtyTypeCode(), "BUILD")) {		//更新房间收益
			updateRoomsEarnings(realtyEarnings);
		}

		realtyEarnings.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(realtyEarningsMapper.updateRealtyEarnings(realtyEarnings), "");
	}

	@Override
	public ServiceReslut deleteRealtyEarnings(RealtyEarnings realtyEarnings) {
		realtyEarnings.setState("0");		//删除状态
		realtyEarnings.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(realtyEarningsMapper.updateRealtyEarnings(realtyEarnings),"");
	}

	@Override
	public List<Map<String, Object>> queryRoomsEarning(RealtyErModel realtyErModel) {
		return realtyEarningsMapper.selectRoomsEarnings(realtyErModel);
	}

	@Override
	public void importEarning(MultipartHttpServletRequest request) {
		try {
			MultipartFile file = request.getFile("file");
			if(file == null) {
				throw new BusinessException("导入失败，导入文件为空", 400, null);
			}
//			File initialFile = new File("C:\\Users\\LENOVO\\Desktop\\znl\\znl.xlsx");
//		    InputStream file = new FileInputStream(initialFile);
			List<Map<String, String>> datas = JExcelReadUtils.readExcelSheet1(file.getInputStream(), -1, 2, -1);
//		    List<Map<String, String>> datas = JExcelReadUtils.readExcelSheet1(file, -1, 2, -1);
			if(CollectionUtils.isEmpty(datas)) {
				throw new BusinessException("导入失败，内容为空", 400, null);
			}

			if(!JExcelReadUtils.checkImprtExcelFormat(datas.get(0), excel_cloum_names)) {
				throw new BusinessException("导入失败，excle 模版错误", 400, null);
			}

			List<RealtyEarnings> realtyEarninges = createEarning(datas);
			if(CollectionUtils.isEmpty(realtyEarninges)) {
				throw new BusinessException("导入失败，内容为空", 400, null);
			}

			for (RealtyEarnings realtyEarnings : realtyEarninges) {
				saveImportEarning(realtyEarnings);
			}
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				throw new BusinessException(e);
			} else {
				throw new BusinessException("导入失败", 400, null);
			}
		}
	}

	private List<RealtyEarnings> createEarning(List<Map<String, String>> datas) {

		List<RealtyEarnings> realtyEarnings = new ArrayList<>();

        Date now = new Date();

		for (int i = 1; i < datas.size(); i++) {
			realtyEarnings.add(createRealtyEarning(datas.get(i), i, now));
		}

		return realtyEarnings;
	}
	//znl 加入修改  对一下
	private RealtyEarnings createRealtyEarning(Map<String, String> data, int row, Date date) {
		//znl注释
//		if(StringUtils.isBlank(data.get("1"))) {
//			throw new BusinessException(String.format("第[%s]条导入失败，客户名称[%s] 客户编号不能为空", row, data.get("0")), 400, null);
//		}
//		Map<String, Object> customerMap = customerService.queryCustomerByCode(data.get("1"));
//		if(customerMap == null) {
//			throw new BusinessException(String.format("第[%s]条导入失败，客户名称[%s] 客户编号[%s]不存在",row, data.get("0"), data.get("1")), 400, null);
//		}

		String buildName = data.get("1");
		if(StringUtils.isBlank(buildName)) {
			throw new BusinessException(String.format("第[%s]条导入失败，客户名称[%s]，楼盘名称不能为空", row, data.get("0")), 400, null);
		}
		String roomNum = data.get("2");
		if(StringUtils.isBlank(buildName)) {
			throw new BusinessException(String.format("第[%s]条导入失败，客户名称[%s]，楼盘名称[%s]房间号不能为空", row, data.get("0"), data.get("1")), 400, null);
		}
		RealtyInfo realtyInfo = new RealtyInfo();
		String customerNameEq =data.get("0");
		realtyInfo.setCustomerNameEq(customerNameEq);
		realtyInfo.setBuildingNameEq(buildName);
		realtyInfo.setRoomNumEq(roomNum);
		List<Map<String, Object>> realtyMaps = realtyInfoService.queryAllRealtyInfo(realtyInfo);
		if(CollectionUtils.isEmpty(realtyMaps)) {
			throw new BusinessException(String.format("第[%s]条导入失败，客户名称[%s] ，楼盘名称[%s]查询失败", row, data.get("0"), buildName), 400, null);
		}

//		List<Map<String, Object>> leasesMaps = getRealtyLeases(realtyMaps.get(0).get("id").toString());
		List<Map<String, Object>> rentMaps = getRealtyLeases(customerNameEq,buildName,roomNum);
//		System.out.println("buildName=="+customerNameEq);
//		System.out.println("customerNameEq=="+String.format("第[%s]条导入失败，客户名称[%s] 客户编号[%s]，楼盘名称[%s]查询租约信息失败", row, data.get("0"), data.get("1"), buildName);
//		if(CollectionUtils.isEmpty(rentMaps)) {
//			throw new BusinessException(String.format("第[%s]条导入失败，客户名称[%s] 客户编号[%s]，楼盘名称[%s]查询租约信息失败", row, data.get("0"), data.get("1"), buildName), 400, null);
//		}
//		if(CollectionUtils.isEmpty(leasesMaps)) {
//			throw new BusinessException(String.format("第[%s]条导入失败，客户名称[%s] 客户编号[%s]，楼盘名称[%s]查询租约信息失败", row, data.get("0"), data.get("1"), buildName), 400, null);
//		}
//		List<Map<String, Object>> rentMaps = getRealtyLeases(customerNameEq,buildName);
		RealtyEarnings realtyEarnings = new RealtyEarnings();
		if(rentMaps!=null&&!rentMaps.isEmpty()) {
			System.out.print("有租约信息");
			realtyEarnings.setRent(new BigDecimal(Double.valueOf(rentMaps.get(0).get("rent").toString())) );
			realtyEarnings.setLeaseManageCost(countLeaseManage(rentMaps));
			realtyEarnings.setRoomEarnings(createRoomJsonStr(rentMaps));
		}else {
			System.out.print("没有租约信息空房的");
			realtyEarnings.setRent(new BigDecimal(Double.valueOf("0")) );
			realtyEarnings.setLeaseManageCost(new BigDecimal(Double.valueOf("0")));
		}
		realtyEarnings.setTaxesCost(new BigDecimal(Double.valueOf(data.get("6"))));
		realtyEarnings.setManageCost(new BigDecimal(Double.valueOf(data.get("7"))));
		realtyEarnings.setFixCost(new BigDecimal(Double.valueOf(data.get("8"))));
		realtyEarnings.setDayCost(new BigDecimal(Double.valueOf(data.get("9"))));
		realtyEarnings.setAgencyCost(new BigDecimal(Double.valueOf(data.get("10"))));
		realtyEarnings.setEqFixCost(new BigDecimal(Double.valueOf(data.get("11"))));
		realtyEarnings.setServiceCost(new BigDecimal(Double.valueOf(data.get("12"))));
		realtyEarnings.setOtherCost(new BigDecimal(Double.valueOf(data.get("13"))));
		realtyEarnings.setDerateCost(new BigDecimal(Double.valueOf(data.get("14"))));

		realtyEarnings.setIncomeCost(countIncomeCost(realtyEarnings));

		Map<String, Object> sessionUser = SecurityContext.getSessionUser();
		realtyEarnings.setCreateUserId((String) sessionUser.get("id"));
		realtyEarnings.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		realtyInfo.setCreateTime(new Date());

		realtyEarnings.setRealtyId(realtyMaps.get(0).get("id").toString());
		realtyEarnings.setBuildingName(realtyMaps.get(0).get("buildingName").toString());
		realtyEarnings.setRealtyTypeCode(realtyMaps.get(0).get("typeCode").toString());
		realtyEarnings.setRealtyTypeValue(realtyMaps.get(0).get("typeValue").toString());
		//znl修改
		realtyEarnings.setCustomerId(realtyMaps.get(0).get("customerId").toString());
		realtyEarnings.setCustomerName(realtyMaps.get(0).get("customerName").toString());
		realtyEarnings.setRoomId(realtyMaps.get(0).get("roomId")!=null?realtyMaps.get(0).get("roomId").toString():null);
		realtyEarnings.setRoomNum(realtyMaps.get(0).get("roomNum")!=null?realtyMaps.get(0).get("roomNum").toString():null);

		realtyEarnings.setState(StringUtils.equals(data.get("5"), "已入账")?"2":"1");
		realtyEarnings.setRemark(data.get("4"));
		realtyEarnings.setAccountDate(data.get("3"));
        realtyEarnings.setCreateTime(date);

		return realtyEarnings;
	}

	private void saveImportEarning(RealtyEarnings realtyEarnings) {
		if(StringUtils.equals(realtyEarnings.getRealtyTypeCode(), "BUILD")) {		//更新房间收益
			updateRoomsEarnings(realtyEarnings);
		}

		realtyEarningsMapper.insertRealtyEarnings(realtyEarnings);
	}

	/**
	 *     查询房间租约信息
	 * @param realtyId
	 * @return
	 */
	private List<Map<String, Object>> getRealtyLeases(String realtyId) {
		RealtyLease realtyLease = new RealtyLease();
		realtyLease.setRealtyId(realtyId);
		realtyLease.setState("1");

		return realtyLeaseService.queryAllRealtyLease(realtyLease);
	}

	private List<Map<String, Object>> getRealtyLeases(String customerNameEq,String buildNameEq,String roomNum) {
		RealtyLease realtyLease = new RealtyLease();
		realtyLease.setCustomerNameEq(customerNameEq);
		realtyLease.setBuildingNameEq(buildNameEq);
		realtyLease.setRoomNum(roomNum);
		realtyLease.setState("1");

		return realtyLeaseService.queryAllRealtyLease(realtyLease);
	}



	/**
	 * 生成房间json
	 * @param leases
	 * @return
	 */
	private String createRoomJsonStr(List<Map<String, Object>> leases) {

		JSONArray leasesJsons = new JSONArray();
		JSONObject leasesJson;
		for (Map<String, Object> lease : leases) {
			leasesJson = new JSONObject();

			leasesJson.put("roomId", lease.get("roomId"));
			leasesJson.put("rent", lease.get("rent"));
			leasesJson.put("leaseMangeCost", lease.get("manageCost"));

			leasesJsons.add(leasesJson);
		}

		return leasesJsons.toJSONString();
	}

	/**
	 * 计算租金
	 * @param leases
	 * @return
	 */
	private BigDecimal countRent(List<Map<String, Object>> leases) {
		BigDecimal rent = new BigDecimal(0);

		for (Map<String, Object> lease : leases) {
			rent = rent.add(new BigDecimal(lease.get("rent").toString()));
		}

		return rent;
	}

	/**
	 * 计算租约管理费
	 * @param leases
	 * @return
	 */
	private BigDecimal countLeaseManage(List<Map<String, Object>> leases) {
		BigDecimal leaseManage = new BigDecimal(0);

		for (Map<String, Object> lease : leases) {
			leaseManage = leaseManage.add(new BigDecimal(lease.get("manageCost").toString()));
		}

		return leaseManage;
	}

	/**
	 * 计算净收入
	 * @param realtyEarnings
	 * @return
	 */
	private BigDecimal countIncomeCost(RealtyEarnings realtyEarnings) {
		return realtyEarnings.getRent().add(realtyEarnings.getLeaseManageCost()).add(realtyEarnings.getDerateCost()).subtract(realtyEarnings.getManageCost())
				.subtract(realtyEarnings.getFixCost()).subtract(realtyEarnings.getDayCost()).subtract(realtyEarnings.getAgencyCost())
				.subtract(realtyEarnings.getEqFixCost()).subtract(realtyEarnings.getServiceCost()).subtract(realtyEarnings.getTaxesCost())
				.subtract(realtyEarnings.getOtherCost());
	}
	public static void main(String[] args) {
		RealtyEarningsServiceImpl t = new RealtyEarningsServiceImpl();
		MultipartHttpServletRequest request=null;
//		t.importEarning(request);
		Map<String,String> map = new HashMap<String,String>();
		map.put("5", "0");
		System.out.println(new BigDecimal(map.get("5")));
	}

}